<template>
    <div>
		<el-dialog :title="title" :visible.sync="open" width="500px" @close="commitOnClose">
			<el-form ref="saveDataform" :model="saveData" :rules="rules" label-width="120px">
				<el-form-item label="员工昵称" prop="nickname">
					<el-input v-model="saveData.nickname" placeholder="请输入员工昵称"/>
				</el-form-item>
				<el-form-item label="员工名称" prop="loginName">
					<el-input v-model="saveData.loginName" placeholder="请输入员工名称"/>
				</el-form-item>
				<el-form-item :label="translate('USER.PHONE')" prop="phone">
					<el-input maxlength="11" v-model="saveData.phone" :placeholder="translate('FROM.PLACEHOLDER', {param: 'USER.PHONE'})"/>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="checkSubmit">{{translate('FROM.SUBMIT')}}</el-button>
				<el-button type="primary" @click="cancel">{{translate('FROM.CANCEL')}}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {UserApi} from '@/api';
	export default {
		name: "CustomForm",
		props: {
			dicts: {
				type: Object,
				default: function () {
					return {}
				}
			},
			isAdd: {
				type: Boolean,
				default: true,
			},
			selectRow: {
				type: Object,
				default: function () {
					return {}
				},
			},
			onFresh: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				title: '',
				saveData: {},
				open: false,
				rules:{
					nickname:[{ required: true, message: '请输入员工昵称', trigger: 'blur' }],
					loginName:[{ required: true, message: '请输入员工名称', trigger: 'blur' }],
					phone:[{ required: true, message: '请输入手机号码', trigger: 'blur' }],
				}
			}
		},
		watch: {
			onFresh: function (value) {
				this.open = value;
				if (value) {
					this.resetData();
				}
			}
		},
		mounted() {
		},
		methods: {
			checkSubmit(){
				this.$refs.saveDataform.validate((valid) => {
                if (valid) {
                   this.submitForm()
                } else {
                    return false;
                }
            });
			},
			async resetData() {
				if (this.isAdd){
					this.title = this.translate('FROM.ADD_MODULE', {module: 'MODULE.USER'});
					this.saveData = {};
				}else {
					this.saveData = this.selectRow;
					this.isAdd = false;
					this.title = this.translate('FROM.UPDATE_MODULE', {module: 'MODULE.USER'});
				}
			},
			async submitForm() {
				let result = (this.isAdd) ? (await UserApi.user.save(this.saveData)) : (await UserApi.user.edit(this.saveData.userId, this.saveData));
				if (result.success) {
					this.Message.success(this.translate(this.isAdd ? 'FROM.ADD_SUCCESS' : 'FROM.UPDATE_SUCCESS'));
					this.commitOnClose();
				}
			},
			cancel() {
				this.saveData = {};
				this.commitOnClose();
			},
			commitOnClose() {
				this.$emit('on-close');
			}
		}
	};
</script>

<style scoped>

</style>
